import { locationName, vertexBuffer } from "./Interface";

interface geoData {
    vertinces: Map<string, verticeData>;
}
//any代指
interface verticeData {
    size: number;
    array: Float32Array;
    buffer?: GPUBuffer;
    needUpdate?: boolean;
}



//集合体对象
//只存储Attrib类型的对象
export default class Geo {
    verticeCount: number = 0;
    vertices: Map<string, verticeData>;

    public constructor(datas: geoData) {
        this.vertices = datas.vertinces!;
    }

    public init(device: GPUDevice) {
        this.initVertices(device);
        this.updateCount();
    }

    private initVertices(device: GPUDevice) {
        const { vertices } = this;

        vertices.forEach(u => {
            const { array } = u;
            const verticesBuffer = device!.createBuffer({
                //缓冲区字节长度
                size: array.byteLength,
                //设置该缓冲区的用途()
                usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
            });
            u.buffer = verticesBuffer;
            u.needUpdate = true;
        });
    }

    public update(device: GPUDevice, renderPass: GPURenderPassEncoder, locationName: Map<string, locationName>) {
        this.updateAttrib(device, renderPass, locationName);
    }

    private updateCount() {
        const { vertices } = this;

        const data = vertices.get('a_Position');
        if (typeof data == 'undefined') {
            console.log(`没有找到[a_Position]`);
        } else {
            const { size, array } = data;
            this.verticeCount = array.length / size;
        }
    }

    private updateAttrib(device: GPUDevice, renderPass: GPURenderPassEncoder, locationName: Map<string, locationName>) {
        const { vertices } = this;
        vertices.forEach((value, key) => {
            const { array, buffer, needUpdate } = value;

            const location = locationName.get(key) as vertexBuffer;
            if (location) {
                if (needUpdate) {
                    device!.queue.writeBuffer(buffer!, 0, array);
                    value.needUpdate = false;
                }
                renderPass.setVertexBuffer(location.location, buffer!);
            } else {
                console.log(`[${key}没有找到对应Location]`);
            }

        });
    }

    public setData(name: string, array: Float32Array) {
        const { vertices } = this;
        const cur = vertices.get(name);
        if (cur) {
            cur.array = array;
        }
    }




}